/**
 * 认证相关API
 */

import request from '@/utils/request'
import type { ApiResponse } from '@/utils/request'

// 登录请求参数
export interface LoginRequest {
  username: string
  password: string
}

// 登录响应数据
export interface LoginResponseData {
  token: string
  refreshToken: string
  expiresIn: number
  userInfo: UserInfo
}

// 用户信息
export interface UserInfo {
  id: string
  username: string
  realName: string
  name?: string  // 添加name字段作为备选
  role: UserRole
  avatar?: string
  phone?: string
  email?: string
  status: UserStatus
  lastLoginTime?: string
  createdTime: string
  schoolId?: string
  classId?: string
}

// 用户角色
export enum UserRole {
  ADMIN = 'ADMIN',
  SCHOOL_ADMIN = 'SCHOOL_ADMIN',
  TEACHER = 'TEACHER',
  PARENT = 'PARENT'
}

// 用户状态
export enum UserStatus {
  ACTIVE = 'ACTIVE',
  SUSPENDED = 'SUSPENDED',
  INACTIVE = 'INACTIVE'
}

// 刷新Token请求
export interface RefreshTokenRequest {
  refreshToken: string
}

// 刷新Token响应
export interface RefreshTokenResponseData {
  token: string
  refreshToken: string
  expiresIn: number
}

// 修改密码请求
export interface ChangePasswordRequest {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

// 注册请求参数（管理员创建用户）
export interface RegisterRequest {
  username: string
  password: string
  realName: string
  role: UserRole
  phone?: string
  email?: string
  schoolId?: string
  classId?: string
}

/**
 * 认证API类
 */
class AuthAPI {
  /**
   * 用户登录
   */
  async login(credentials: LoginRequest): Promise<ApiResponse<LoginResponseData>> {
    return request.post<LoginResponseData>('/api/v1/auth/login', credentials, {
      showLoading: true,
      loadingText: '登录中...',
      showError: true,
      skipAuth: true  // 登录接口不需要Authorization头
    })
  }

  /**
   * 家长登录（手机号/用户名 + 学生信息）
   */
  async parentLogin(credentials: {
    username: string
    password: string
    studentName?: string
    studentClass?: string
  }): Promise<ApiResponse<LoginResponseData>> {
    return request.post<LoginResponseData>('/api/v1/auth/parent-login', credentials, {
      showLoading: true,
      loadingText: '登录中...',
      showError: true,
      skipAuth: true  // 家长登录接口也不需要Authorization头
    })
  }

  /**
   * 用户登出
   */
  async logout(): Promise<ApiResponse<void>> {
    return request.post<void>('/api/v1/auth/logout', {}, {
      showLoading: false,
      showError: false
    }).catch(() => {
      // 登出接口失败也返回成功，避免前端卡死
      return { code: 200, message: '登出成功', data: undefined, timestamp: new Date().toISOString() }
    })
  }

  /**
   * 刷新Token
   */
  async refreshToken(refreshToken: string): Promise<ApiResponse<RefreshTokenResponseData>> {
    return request.post<RefreshTokenResponseData>('/api/v1/auth/refresh', {
      refreshToken
    }, {
      showLoading: false,
      showError: false,
      skipAuth: true  // 刷新Token接口不需要Authorization头
    })
  }

  /**
   * 修改密码
   */
  async changePassword(data: ChangePasswordRequest): Promise<ApiResponse<void>> {
    return request.post<void>('/api/v1/auth/change-password', data, {
      showLoading: true,
      loadingText: '修改中...',
      showError: true
    })
  }

  /**
   * 用户注册（管理员功能）
   */
  async register(userData: RegisterRequest): Promise<ApiResponse<UserInfo>> {
    return request.post<UserInfo>('/api/v1/auth/register', userData, {
      showLoading: true,
      loadingText: '创建中...',
      showError: true
    })
  }

  /**
   * 获取当前用户信息
   */
  async getCurrentUser(): Promise<ApiResponse<UserInfo>> {
    return request.get<UserInfo>('/api/users/current', {}, {
      showLoading: false,
      showError: true
    })
  }

  /**
   * 更新用户信息
   */
  async updateProfile(profileData: Partial<UserInfo>): Promise<ApiResponse<UserInfo>> {
    return request.put<UserInfo>('/api/users/current', profileData, {
      showLoading: true,
      loadingText: '更新中...',
      showError: true
    })
  }
}

// 创建API实例
export const authAPI = new AuthAPI()

// 默认导出
export default authAPI

/**
 * 角色相关工具函数
 */
export const roleUtils = {
  /**
   * 获取角色显示名称
   */
  getRoleDisplayName(role: UserRole): string {
    const roleNames = {
      [UserRole.ADMIN]: '超级管理员',
      [UserRole.SCHOOL_ADMIN]: '学校管理员',
      [UserRole.TEACHER]: '班主任',
      [UserRole.PARENT]: '家长'
    }
    return roleNames[role] || '未知角色'
  },

  /**
   * 获取角色图标
   */
  getRoleIcon(role: UserRole): string {
    const roleIcons = {
      [UserRole.ADMIN]: '👑',
      [UserRole.SCHOOL_ADMIN]: '🏫',
      [UserRole.TEACHER]: '👨‍🏫',
      [UserRole.PARENT]: '👨‍👩‍👧‍👦'
    }
    return roleIcons[role] || '👤'
  },

  /**
   * 检查是否为管理员角色
   */
  isAdmin(role: UserRole): boolean {
    return [UserRole.ADMIN, UserRole.SCHOOL_ADMIN].includes(role)
  },

  /**
   * 检查是否为教师角色
   */
  isTeacher(role: UserRole): boolean {
    return role === UserRole.TEACHER
  },

  /**
   * 检查是否为家长角色
   */
  isParent(role: UserRole): boolean {
    return role === UserRole.PARENT
  },

  /**
   * 根据角色获取首页路径
   */
  getHomePathByRole(role: UserRole): string {
    const homePaths: Record<UserRole, string> = {
      [UserRole.ADMIN]: '/pages/admin/dashboard',
      [UserRole.SCHOOL_ADMIN]: '/pages/admin/dashboard',
      [UserRole.TEACHER]: '/pages/teacher/dashboard',
      [UserRole.PARENT]: '/pages/parent/dashboard'
    }
    return homePaths[role] || '/pages/index/index'
  },

  /**
   * 获取角色权限列表
   */
  getRolePermissions(role: UserRole): string[] {
    const permissions: Record<UserRole, string[]> = {
      [UserRole.ADMIN]: [
        'user:read', 'user:create', 'user:update', 'user:delete',
        'class:read', 'class:create', 'class:update', 'class:delete',
        'student:read', 'student:create', 'student:update', 'student:delete',
        'record:read', 'record:create', 'record:update', 'record:delete',
        'notification:read', 'notification:create', 'notification:update', 'notification:delete',
        'system:read', 'system:update'
      ],
      [UserRole.SCHOOL_ADMIN]: [
        'user:read', 'user:update',
        'class:read', 'class:create', 'class:update', 'class:delete',
        'student:read', 'student:create', 'student:update', 'student:delete',
        'record:read', 'record:create', 'record:update', 'record:delete',
        'notification:read', 'notification:create', 'notification:update',
        'system:read'
      ],
      [UserRole.TEACHER]: [
        'student:read', 'student:create', 'student:update',
        'record:read', 'record:create', 'record:update', 'record:delete',
        'notification:read', 'notification:create'
      ],
      [UserRole.PARENT]: [
        'student:read',
        'record:read',
        'notification:read'
      ]
    }
    return permissions[role] || []
  }
}
